#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "util.h"

#include "rendermanager.h"
#include "calldialog.h"

#include <QStandardItemModel>
#include <QListView>
#include <QMessageBox>



//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
MainWindow::MainWindow(const std::string& user_id, SdkManager* sdk_mgr, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_user_id(user_id)
    , m_sdk_mgr(sdk_mgr)
{
    ui->setupUi(this);
    ui->label_user_id->setText(QString::fromStdString(m_user_id));

    // 设置 contentLayout 的左右比例 1:5
    ui->contentLayout->setStretch(0, 1); // leftLayout
    ui->contentLayout->setStretch(1, 5); // rightLayout

    // 设置 leftLayout 的拉伸因子，groupBox_message 填充剩余空间
    ui->leftLayout->setStretch(0, 0); // groupBox_user
    ui->leftLayout->setStretch(1, 0); // pushButton_call
    ui->leftLayout->setStretch(2, 0); // groupBox_room
    ui->leftLayout->setStretch(3, 1); // groupBox_message

	// 初始化示例用户 ID 和呼叫状态
	//setUserId("User123");
	//setCallState("Connected");

	m_sdk_mgr->RegisterIncomingCallHandler(
		[this](const std::string& call_type, const std::string& user_id, const std::string& call_id) -> bool {
			return OnIncomingCall(call_type, user_id, call_id);
		});
    m_sdk_mgr->RegisterCallStateChangedHandler(
        [this](const std::string& call_id, CallState state) {
            OnCallStateChanged(call_id, state);
		});
	m_sdk_mgr->RegisterUserAddHandler(
		[this](const std::string& user_id) {
			OnAddUser(user_id);
		});
	m_sdk_mgr->RegisterUserRemoveHandler(
		[this](const std::string& user_id) {
			OnRemoveUser(user_id);
		});
	m_sdk_mgr->RegisterStartPublishNotifyHandler(
		[this](const std::string& user_id, const MediaInfo& media) {
			OnStartPublishNotify(user_id, media);
		});
	m_sdk_mgr->RegisterStopPublishNotifyHandler(
		[this](const std::string& user_id, const MediaInfo& media) {
			OnStopPublishNotify(user_id, media);
		});
	m_sdk_mgr->RegisterStartSubscribeResultHandler(
		[this](const std::string& user_id, const MediaInfo& media, bool result) {
			OnStartSubscribeResult(user_id, media, result);
		});
	m_sdk_mgr->RegisterStopSubscribeResultHandler(
		[this](const std::string& user_id, const MediaInfo& media, bool result) {
			OnStopSubscribeResult(user_id, media, result);
		});
	m_sdk_mgr->RegisterStartPublishResultHandler(
		[this](const MediaInfo& media, bool result) {
			OnStartPublishResult(media, result);
		});
	m_sdk_mgr->RegisterStopPublishResultHandler(
		[this](const MediaInfo& media, bool result) {
			OnStopPublishResult(media, result);
		});

    connect(ui->pushButton_call, &QPushButton::clicked, this, &MainWindow::OnCallBtnClicked);
    connect(ui->pushButton_cam, &QPushButton::clicked, this, &MainWindow::OnPubCamBtnClicked);
    connect(ui->pushButton_mic, &QPushButton::clicked, this, &MainWindow::OnPubMicBtnClicked);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
MainWindow::~MainWindow()
{
	m_sdk_mgr->RegisterIncomingCallHandler(nullptr);
    m_sdk_mgr->RegisterCallStateChangedHandler(nullptr);
	m_sdk_mgr->RegisterUserAddHandler(nullptr);
	m_sdk_mgr->RegisterUserRemoveHandler(nullptr);
	m_sdk_mgr->RegisterStartPublishNotifyHandler(nullptr);
	m_sdk_mgr->RegisterStopPublishNotifyHandler(nullptr);
	m_sdk_mgr->RegisterStartSubscribeResultHandler(nullptr);
	m_sdk_mgr->RegisterStopSubscribeResultHandler(nullptr);
	m_sdk_mgr->RegisterStartPublishResultHandler(nullptr);
	m_sdk_mgr->RegisterStopPublishResultHandler(nullptr);

    delete ui;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::Init()
{
    RenderManager::Instance().Init(ui->container_video, m_sdk_mgr);

    // 填充摄像头
    auto cams = m_sdk_mgr->GetVideoInputDevList();
    for (const auto& cam : cams) {
        ui->comboBox_cam->addItem(QString::fromStdString(cam.name), QString::fromStdString(cam.id));
    }

    // 填充麦克风
    auto mics = m_sdk_mgr->GetAudioInputDevList();
    for (const auto& mic : mics) {
        ui->comboBox_mic->addItem(QString::fromStdString(mic.name), QString::fromStdString(mic.id));
    }

    // 填充扬声器
    auto spks = m_sdk_mgr->GetAudioOutputDevList();
    for (const auto& spk : spks) {
        ui->comboBox_spk->addItem(QString::fromStdString(spk.name), QString::fromStdString(spk.id));
    }

    // 填充用户列表
    QStandardItemModel *model = new QStandardItemModel(this);
    ui->listView_user->setModel(model);
    auto users = m_sdk_mgr->GetUserList();
    for (const std::string& user : users) {
        model->appendRow(new QStandardItem(QString::fromStdString(user)));
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::resizeEvent(QResizeEvent* event)
{
    qDebug() << "MainWindow::resizeEvent";

    QMainWindow::resizeEvent(event); // 保持父类行为
    RenderManager::Instance().UpdateRenderDisplay();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::moveEvent(QMoveEvent* event)
{
    qDebug() << "MainWindow::moveEvent";
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnAddUser(const std::string& user_id)
{
    auto model = qobject_cast<QStandardItemModel *>(ui->listView_user->model());
    if (model) {
        model->appendRow(new QStandardItem(QString::fromStdString(user_id)));
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnRemoveUser(const std::string& user_id)
{
    auto model = qobject_cast<QStandardItemModel *>(ui->listView_user->model());
    if (model) {
        for (int row = 0; row < model->rowCount(); ++row) {
            QStandardItem *item = model->item(row);
            if (item && item->text() == QString::fromStdString(user_id)) {
                model->removeRow(row);
                break; // 删除后需要 break，否则索引会变化
            }
        }
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnStartPublishNotify(const std::string& user_id, const MediaInfo& media)
{
    if (!m_sdk_mgr->StartSubscribe(user_id, media)) {
        QMessageBox::warning(this, "错误", "订阅媒体失败");
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
bool MainWindow::OnIncomingCall(const std::string& call_type, const std::string& user_id,
                                const std::string& call_id)
{
    if (m_calling) {
        ShowToast("正在呼叫中，已拒绝新来的呼叫", this);
        return false;
    }

    ui->label_call_state->setText("Incoming");

	QString msg = QString("来自 %1 的 %2 呼叫").arg(QString::fromStdString(user_id), 
		QString::fromStdString(call_type));

    QMessageBox::StandardButton reply = QMessageBox::question(
        this,
        "来电",
        msg,
        QMessageBox::Yes | QMessageBox::No,
        QMessageBox::No
    );

    if (reply == QMessageBox::Yes) {
        m_calling = true;
        ui->pushButton_call->setText("挂断");
        ui->label_call_state->setText("Connected");
    } else {
        ui->label_call_state->setText("Idle");
    }
	
    return reply == QMessageBox::Yes;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnCallStateChanged(const std::string& call_id, CallState state)
{
    if (state == CallState::Terminated) {
        if (m_calling) {
            m_sdk_mgr->StopRenderAll();
            m_calling = false;
            ui->pushButton_call->setText("呼叫");
            ui->label_call_state->setText("Idle");
        }
    } else if (state == CallState::Connected) {
        ui->label_call_state->setText("Connected");
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnStopPublishNotify(const std::string& user_id, const MediaInfo& media)
{
    if (media.media_type == "video" && !m_sdk_mgr->StopRender(media)) {
        QMessageBox::warning(this, "错误", "停止渲染失败");
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnStartSubscribeResult(const std::string& user_id, const MediaInfo& media,
                                        bool result)
{
    if (result) {
        if (media.media_type == "video" && !m_sdk_mgr->StartRender(media)) {
            QMessageBox::warning(this, "错误", "启动渲染失败");
        } else {
            ShowToast("订阅媒体成功", this);
        }
    } else {
        QMessageBox::warning(this, "错误", "订阅媒体失败");
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnStopSubscribeResult(const std::string& user_id, const MediaInfo& media,
                                       bool result)
{
	if (result) {
		ShowToast("取消订阅媒体成功", this);
	} else {
		ShowToast("取消订阅媒体失败", this);
	}
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnStartPublishResult(const MediaInfo& media, bool result)
{
    if (media.media_type == "video") {
        if (result) {
            m_pub_cam = true;
            ui->pushButton_cam->setText("关闭摄像头");
            ShowToast("摄像头已开启", this);
        } else {
            QMessageBox::warning(this, "错误", "开启摄像头失败");
        }
    } else if (media.media_type == "audio") {
        if (result) {
            m_pub_mic = true;
            ui->pushButton_mic->setText("关闭麦克风");
            ShowToast("麦克风已开启", this);
        } else {
            QMessageBox::warning(this, "错误", "开启麦克风失败");
        }
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnStopPublishResult(const MediaInfo& media, bool result)
{
    if (media.media_type == "video") {
        if (result) {
            m_pub_cam = false;
            ui->pushButton_cam->setText("打开摄像头");
        } else {
            QMessageBox::warning(this, "错误", "关闭摄像头失败");
        }
    } else if (media.media_type == "audio") {
        if (result) {
            m_pub_mic = false;
            ui->pushButton_mic->setText("打开麦克风");
        } else {
            QMessageBox::warning(this, "错误", "关闭麦克风失败");
        }
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnCallBtnClicked()
{
    if (m_calling) {
        m_sdk_mgr->TerminateCall();

        m_calling = false;
        ui->pushButton_call->setText("呼叫");
        ui->label_call_state->setText("Terminating");

        if (m_pub_cam) {
            m_pub_cam = false;
            ui->pushButton_cam->setText("打开摄像头");
        }
    } else {
        CallDialog dialog(m_sdk_mgr);
        int ret = dialog.exec();
		if (ret == QDialog::Accepted) {
			m_calling = true;
        	ui->pushButton_call->setText("挂断");
            ui->label_call_state->setText("Outgoing");
		} else {
			ShowToast("呼叫失败", this);
		}
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnPubCamBtnClicked()
{
    if (m_pub_cam) {
        m_sdk_mgr->StopPublishVideo(m_cam_media);
    } else {
        MediaDev dev;
        dev.id = ui->comboBox_cam->currentData().toString().toStdString();
        dev.name = ui->comboBox_cam->currentText().toStdString();

        if (!m_sdk_mgr->StartPublishVideo(dev, m_cam_media)) {
            QMessageBox::warning(this, "错误", "广播摄像头失败");
        }
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void MainWindow::OnPubMicBtnClicked()
{
    if (m_pub_mic) {
        m_sdk_mgr->StopPublishAudio(m_mic_media);
    } else {
        MediaDev dev;
        dev.id = ui->comboBox_mic->currentData().toString().toStdString();
        dev.name = ui->comboBox_mic->currentText().toStdString();

        if (!m_sdk_mgr->StartPublishAudio(dev, m_mic_media)) {
            QMessageBox::warning(this, "错误", "广播麦克风失败");
        }
    }
}
